document.addEventListener('DOMContentLoaded', function () {
    // 获取Canvas元素和上下文
    const canvas = document.getElementById('animationCanvas');
    const ctx = canvas.getContext('2d');

    // 动画状态
    const animationState = {
        henPosition: { x: -100, y: 0 },
        henTargetX: 0, // 母鸡目标位置
        isWalking: false, // 母鸡是否在行走
        isLaying: false, // 母鸡是否在下蛋
        eggCount: 0, // 鸡蛋数量
        layCount: 0, // 下蛋次数
        eggs: [], // 鸡蛋数组
        eggColors: ['#F3F4F6', '#FBBF24', '#1F2937'], // 鸡蛋颜色: 白、黄、黑
        status: 'ready', // 状态: ready, walking, laying, resting, full
        lastUpdateTime: 0, // 上次更新时间
        animationId: null, // 动画ID
    };

    // 设置Canvas尺寸为容器大小
    function resizeCanvas() {
        const container = canvas.parentElement;
        canvas.width = container.clientWidth;
        canvas.height = container.clientHeight;
        // 重绘场景
        drawScene();
    }

    // 监听窗口大小变化，调整Canvas尺寸
    window.addEventListener('resize', resizeCanvas);
    resizeCanvas();

    // 绘制场景
    function drawScene(timestamp) {
        // 清除Canvas
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 绘制背景
        drawBackground();

        // 绘制草地
        drawGrass();

        // 绘制云朵
        drawClouds();

        // 绘制鸡窝
        drawNest();

        // 绘制鸡蛋
        drawEggs();

        // 更新和绘制母鸡
        updateHen(timestamp);
        drawHen();

        // 更新UI状态
        updateUI();

        // 继续动画循环
        animationState.animationId = requestAnimationFrame(drawScene);
    }

    // 绘制背景
    function drawBackground() {
        // 绘制渐变天空
        const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
        gradient.addColorStop(0, '#93C5FD'); // 浅蓝色
        gradient.addColorStop(1, '#DBEAFE'); // 更浅的蓝色
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    }

    // 绘制草地
    function drawGrass() {
        const grassHeight = canvas.height * 0.2;

        // 绘制草地
        ctx.fillStyle = '#10B981'; // 绿色
        ctx.fillRect(0, canvas.height - grassHeight, canvas.width, grassHeight);

        // 绘制草丛
        ctx.fillStyle = '#14B8A6'; // 深一点的绿色
        for (let i = 0; i < 20; i++) {
            const x = Math.random() * canvas.width;
            const width = 10 + Math.random() * 20;
            const height = 15 + Math.random() * 30;

            ctx.beginPath();
            ctx.moveTo(x, canvas.height - grassHeight);
            ctx.bezierCurveTo(
                x + width / 2, canvas.height - grassHeight - height,
                x - width / 2, canvas.height - grassHeight - height / 2,
                x, canvas.height - grassHeight
            );
            ctx.fill();
        }
    }

    // 绘制云朵
    function drawClouds() {
        ctx.fillStyle = 'white';

        // 云的位置和大小
        const clouds = [
            { x: canvas.width * 0.1, y: canvas.height * 0.1, size: 50 },
            { x: canvas.width * 0.4, y: canvas.height * 0.05, size: 60 },
            { x: canvas.width * 0.7, y: canvas.height * 0.15, size: 40 },
            { x: canvas.width * 0.9, y: canvas.height * 0.08, size: 55 }
        ];

        // 绘制每朵云
        clouds.forEach(cloud => {
            // 绘制圆形组合成云
            drawCloud(cloud.x, cloud.y, cloud.size);
        });
    }

    // 绘制单个云
    function drawCloud(x, y, size) {
        ctx.beginPath();

        // 绘制几个重叠的圆形形成云的形状
        ctx.arc(x, y, size, 0, Math.PI * 2);
        ctx.arc(x + size * 0.7, y - size * 0.3, size * 0.8, 0, Math.PI * 2);
        ctx.arc(x + size * 1.4, y, size * 0.7, 0, Math.PI * 2);
        ctx.arc(x + size * 0.7, y + size * 0.3, size * 0.6, 0, Math.PI * 2);

        ctx.fill();

        // 添加一些阴影效果
        ctx.strokeStyle = 'rgba(255, 255, 255, 0.7)';
        ctx.lineWidth = 2;
        ctx.stroke();
    }

    // 绘制鸡窝
    function drawNest() {
        // 鸡窝位置和大小
        const nestX = canvas.width / 2;
        const nestY = canvas.height * 0.7;
        const nestWidth = 120;
        const nestHeight = 60;

        // 绘制鸡窝底部
        ctx.fillStyle = '#8B5CF6'; // 紫色
        ctx.beginPath();
        ctx.ellipse(nestX, nestY, nestWidth, nestHeight / 2, 0, 0, Math.PI * 2);
        ctx.fill();

        // 绘制鸡窝边缘
        ctx.strokeStyle = '#6D28D9'; // 深紫色
        ctx.lineWidth = 5;
        ctx.beginPath();
        ctx.ellipse(nestX, nestY - nestHeight / 4, nestWidth * 0.9, nestHeight * 0.4, 0, 0, Math.PI * 2);
        ctx.stroke();

        // 绘制稻草
        ctx.fillStyle = '#D4AF37'; // 金色
        for (let i = 0; i < 15; i++) {
            const startX = nestX - nestWidth + Math.random() * nestWidth * 2;
            const startY = nestY - nestHeight / 4 + Math.random() * 10;
            const endX = startX + (Math.random() * 40 - 20);
            const endY = startY - (Math.random() * 30 + 10);

            ctx.beginPath();
            ctx.moveTo(startX, startY);
            ctx.bezierCurveTo(
                startX + (endX - startX) / 3, startY - 10,
                startX + 2 * (endX - startX) / 3, endY + 10,
                endX, endY
            );
            ctx.stroke();
        }

        // 保存鸡窝位置，母鸡将移动到这里
        if (typeof animationState !== 'undefined') {
            animationState.henTargetX = nestX - 40; // 母鸡位置调整
        }
    }

    // 绘制母鸡
    function drawHen() {
        const henX = animationState.henPosition.x;
        const henY = animationState.henPosition.y;

        // 母鸡身体
        ctx.fillStyle = '#F97316'; // 橙色
        ctx.beginPath();
        ctx.ellipse(henX, henY, 40, 30, 0, 0, Math.PI * 2);
        ctx.fill();

        // 母鸡头部
        ctx.beginPath();
        ctx.arc(henX + 45, henY - 5, 20, 0, Math.PI * 2);
        ctx.fill();

        // 母鸡眼睛
        ctx.fillStyle = 'black';
        ctx.beginPath();
        ctx.arc(henX + 50, henY - 10, 5, 0, Math.PI * 2);
        ctx.fill();

        // 母鸡嘴
        ctx.fillStyle = '#FBBF24'; // 黄色
        ctx.beginPath();
        ctx.moveTo(henX + 60, henY - 5);
        ctx.lineTo(henX + 70, henY);
        ctx.lineTo(henX + 60, henY + 5);
        ctx.closePath();
        ctx.fill();

        // 母鸡鸡冠
        ctx.fillStyle = '#EF4444'; // 红色
        ctx.beginPath();
        ctx.moveTo(henX + 45, henY - 25);
        ctx.lineTo(henX + 50, henY - 35);
        ctx.lineTo(henX + 55, henY - 25);
        ctx.closePath();
        ctx.fill();

        // 母鸡翅膀
        if (animationState.isWalking) {
            // 行走时翅膀摆动
            const wingAngle = Math.sin(Date.now() * 0.01) * 0.2;
            ctx.save();
            ctx.translate(henX, henY);
            ctx.rotate(wingAngle);

            ctx.fillStyle = '#FB923C'; // 浅橙色
            ctx.beginPath();
            ctx.ellipse(-25, 0, 25, 15, 0, 0, Math.PI * 2);
            ctx.fill();

            ctx.restore();
        } else {
            // 站立时翅膀下垂
            ctx.fillStyle = '#FB923C'; // 浅橙色
            ctx.beginPath();
            ctx.ellipse(henX - 25, henY + 5, 25, 15, 0, 0, Math.PI * 2);
            ctx.fill();
        }

        // 母鸡腿
        ctx.strokeStyle = '#FBBF24'; // 黄色
        ctx.lineWidth = 5;

        if (animationState.isLaying) {
            // 下蛋时蹲下，腿变短
            ctx.beginPath();
            ctx.moveTo(henX - 15, henY + 30);
            ctx.lineTo(henX - 15, henY + 40);
            ctx.stroke();

            ctx.beginPath();
            ctx.moveTo(henX + 15, henY + 30);
            ctx.lineTo(henX + 15, henY + 40);
            ctx.stroke();
        } else {
            // 正常站立时的腿
            ctx.beginPath();
            ctx.moveTo(henX - 15, henY + 30);
            ctx.lineTo(henX - 15, henY + 50);
            ctx.stroke();

            ctx.beginPath();
            ctx.moveTo(henX + 15, henY + 30);
            ctx.lineTo(henX + 15, henY + 50);
            ctx.stroke();
        }

        // 母鸡尾巴
        ctx.fillStyle = '#F97316'; // 橙色
        ctx.beginPath();
        ctx.moveTo(henX - 40, henY);
        ctx.lineTo(henX - 50, henY - 15);
        ctx.lineTo(henX - 50, henY + 15);
        ctx.closePath();
        ctx.fill();

        // 如果正在下蛋，绘制下蛋动画
        if (animationState.isLaying) {
            // 鸡蛋位置在母鸡下方
            const eggX = henX + 10;
            const eggY = henY + 35;

            // 随机选择鸡蛋颜色
            const eggColor = animationState.eggColors[Math.floor(Math.random() * animationState.eggColors.length)];

            // 绘制鸡蛋
            drawEgg(eggX, eggY, eggColor, true);
        }
    }

    // 绘制鸡蛋
    function drawEgg(x, y, color, isLaying = false) {
        ctx.fillStyle = color;

        // 绘制鸡蛋形状
        ctx.beginPath();
        ctx.ellipse(x, y, 15, 20, 0, 0, Math.PI * 2);
        ctx.fill();

        // 如果是正在下蛋的动画，添加一些特殊效果
        if (isLaying) {
            // 添加一些光泽效果
            ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
            ctx.beginPath();
            ctx.ellipse(x - 5, y - 10, 5, 8, 0, 0, Math.PI * 2);
            ctx.fill();
        } else {
            // 静态鸡蛋添加一些细节
            ctx.fillStyle = 'rgba(255, 255, 255, 0.2)';
            ctx.beginPath();
            ctx.ellipse(x - 4, y - 8, 4, 6, 0, 0, Math.PI * 2);
            ctx.fill();
        }
    }

    // 绘制所有鸡蛋
    function drawEggs() {
        // 鸡蛋在鸡窝中的位置
        const nestX = canvas.width / 2;
        const nestY = canvas.height * 0.7 - 10;

        // 鸡蛋之间的间距
        const eggSpacing = 30;

        // 绘制已有的鸡蛋
        animationState.eggs.forEach((egg, index) => {
            // 计算鸡蛋位置，使它们在鸡窝中均匀分布
            const xOffset = (index - (animationState.eggs.length - 1) / 2) * eggSpacing;
            const eggX = nestX + xOffset;
            const eggY = nestY;

            // 绘制鸡蛋
            drawEgg(eggX, eggY, egg.color);
        });
    }

    // 更新母鸡位置和状态
    function updateHen(timestamp) {
        if (!animationState.lastUpdateTime) {
            animationState.lastUpdateTime = timestamp;
            return;
        }

        const deltaTime = timestamp - animationState.lastUpdateTime;
        animationState.lastUpdateTime = timestamp;

        const henSpeed = 0.3; // 母鸡移动速度

        // 根据当前状态更新母鸡行为
        switch (animationState.status) {
            case 'ready':
                // 准备状态，等待开始命令
                break;

            case 'walking':
                // 行走状态，移动到鸡窝
                animationState.isWalking = true;

                // 移动母鸡
                if (animationState.henPosition.x < animationState.henTargetX) {
                    animationState.henPosition.x += henSpeed * deltaTime;

                    // 到达目标位置
                    if (animationState.henPosition.x >= animationState.henTargetX) {
                        animationState.henPosition.x = animationState.henTargetX;
                        animationState.status = 'laying';
                        animationState.isWalking = false;
                        animationState.isLaying = true;

                        // 延迟一下开始下蛋
                        setTimeout(() => {
                            // 添加新鸡蛋
                            addEgg();
                            animationState.isLaying = false;

                            // 检查鸡蛋数量
                            if (animationState.eggCount >= 3) {
                                animationState.status = 'full';
                            } else {
                                // 下蛋后休息一下
                                animationState.status = 'resting';

                                // 休息一段时间后回到初始位置
                                setTimeout(() => {
                                    animationState.henPosition.x = -100;
                                    animationState.status = 'ready';
                                }, 2000);
                            }
                        }, 1000);
                    }
                }
                break;

            case 'laying':
                // 下蛋状态，母鸡静止
                break;

            case 'resting':
                // 休息状态，母鸡静止
                break;

            case 'full':
                // 鸡蛋满了，母鸡静止
                animationState.isWalking = false;
                break;
        }
    }

    // 添加新鸡蛋
    function addEgg() {
        if (animationState.eggCount >= 3) {
            return; // 最多3个鸡蛋
        }

        // 随机选择鸡蛋颜色
        const colorIndex = Math.floor(Math.random() * animationState.eggColors.length);
        const color = animationState.eggColors[colorIndex];

        // 添加鸡蛋到数组
        animationState.eggs.push({ color });
        animationState.eggCount++;
        animationState.layCount++;
    }

    // 更新UI状态
    function updateUI() {
        document.getElementById('eggCount').textContent = `${animationState.eggCount}/3`;
        document.getElementById('layCount').textContent = animationState.layCount;

        // 更新状态文本
        let statusText = '';
        switch (animationState.status) {
            case 'ready':
                statusText = '准备中';
                break;
            case 'walking':
                statusText = '走向鸡窝';
                break;
            case 'laying':
                statusText = '正在下蛋';
                break;
            case 'resting':
                statusText = '休息中';
                break;
            case 'full':
                statusText = '鸡窝已满';
                break;
        }

        document.getElementById('status').textContent = statusText;
    }

    // 开始下蛋
    function startLaying() {
        if (animationState.status === 'ready' && animationState.eggCount < 3) {
            animationState.status = 'walking';
        }
    }

    // 重置动画
    function resetAnimation() {
        // 重置动画状态
        animationState.henPosition = { x: -100, y: 0 };
        animationState.isWalking = false;
        animationState.isLaying = false;
        animationState.eggCount = 0;
        animationState.layCount = 0;
        animationState.eggs = [];
        animationState.status = 'ready';

        // 更新UI
        updateUI();
    }

    // 初始化事件监听器
    function initEventListeners() {
        // 开始按钮点击事件
        document.getElementById('startBtn').addEventListener('click', startLaying);

        // 重置按钮点击事件
        document.getElementById('resetBtn').addEventListener('click', resetAnimation);
    }

    // 启动动画
    function startAnimation() {
        // 开始动画循环
        animationState.animationId = requestAnimationFrame(drawScene);

        // 初始化事件监听器
        initEventListeners();
    }

    // 启动动画
    startAnimation();
});